<?php
load()->func('tpl');
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$_W['page']['title'] = '优惠券记录';
//创建奖品记录表
//pdo_query("CREATE TABLE IF NOT EXISTS `ims_tg_prize` (
//      `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
//      `uniacid` int(10) unsigned NOT NULL COMMENT '公众账号id',
//      `idcard` varchar(100) NOT NULL COMMENT '身份证号',
//      `prize_user` varchar(100) NOT NULL COMMENT '发奖人',
//      `prize_time` int(11) NOT NULL COMMENT '发奖时间',
//      `prize_times` int(11) NOT NULL COMMENT '领奖时参加活动次数',
//      PRIMARY KEY (`id`),
//      KEY `idx_uniacid` (`uniacid`)
//    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
//    ");
//// TODO 添加领奖字段
//if (!pdo_fieldexists('tg_favorabler', 'prize')) {
//    pdo_query("ALTER TABLE " . tablename('tg_favorabler') . " ADD `prize` int(1) NOT NULL default 0 COMMENT '领奖';");
//}
//// TODO 添加领券时间字段
//if (!pdo_fieldexists('tg_favorabler', 'createtime')) {
//    pdo_query("ALTER TABLE " . tablename('tg_favorabler') . " ADD `createtime` int(11) NOT NULL COMMENT '领券时间';");
//}
//// TODO 添加卡券核销次数字段
//if (!pdo_fieldexists('tg_member', 'favorable_times')) {
//    pdo_query("ALTER TABLE " . tablename('tg_member') . " ADD `favorable_times` int(11) NOT NULL default 0 COMMENT '卡券核销次数';");
//}
//// TODO 添加项目核销次数字段
//if (!pdo_fieldexists('tg_member', 'order_times')) {
//    pdo_query("ALTER TABLE " . tablename('tg_member') . " ADD `order_times` int(11) NOT NULL default 0 COMMENT '项目核销次数';");
//}
//// TODO 添加卡券发奖次数字段
//if (!pdo_fieldexists('tg_member', 'prize_times')) {
//    pdo_query("ALTER TABLE " . tablename('tg_member') . " ADD `prize_times` int(11) NOT NULL default 0 COMMENT '卡券发奖次数';");
//}

//if ($operation == 'hexiao') {
//    if ($_W['uniacid'] == 6) {
////        $hexiao = pdo_fetchall("select * from " . tablename('tg_hexiao') . " where uniacid = '{$_W['uniacid']}'");
//        $hexiao = pdo_fetchall("select count(id) as cid , openid , uniacid from " . tablename('tg_favorabler') . " where uniacid = '{$_W['uniacid']}' and status = 1 group by openid ");
//        foreach ($hexiao as &$item) {
////            if (empty($item['favorabler_id'])) {
////                pdo_update('tg_member', array('favorable_times +=' => 1), array('uniacid' => $item['uniacid'], 'openid' => $item['openid']));
//                pdo_update('tg_member', array('favorable_times' => $item['cid']), array('uniacid' => $item['uniacid'], 'openid' => $item['openid']));
////            }
////            elseif (empty($item['orderno'])){
////                pdo_update('tg_member' , array('order_times +=' => 1) , array('uniacid' => $item['uniacid'] , 'openid' => $item['openid']));
////            }
//
//        }
//        die(json_encode(1));
//    }
//}

if ($operation == 'display') {

    $size = 10;
    $page = !empty($_GPC['page']) ? $_GPC['page'] : 1;
//    $coupon = '';
//    $member = '';
//    $status = '';
//    $time = '';
    $bb = '';
    if (!empty($_GPC['time'])) {
        $time = $_GPC['time'];
        $start = strtotime($time['start']);
        $end = strtotime($time['end']);
        $bb .= " and createtime > '{$start}' and createtime < '{$end}'";

    }
    if (!empty($_GPC['coupon'])) {
        $c = trim($_GPC['coupon']);
        $keyword .= " and name LIKE '%{$_GPC['coupon']}%' ";

//        $aa = pdo_fetchall('select id from ' . tablename('tg_favorable') . " where uniacid = {$_W['uniacid']} {$keyword}");
//        $ee = pdo_fetchall('select id from ' . tablename('tg_member') . " where uniacid = {$_W['uniacid']} {$keyword1}");
        $bb .= " and favorable_id in ( select id from " . tablename('tg_favorable') . " where uniacid = {$_W['uniacid']} {$keyword} )";
    }
    if (!empty($_GPC['member'])) {
        $mem = trim($_GPC['member']);
        $key = " and ( realname like '%{$_GPC['member']}%' or mobile like '%{$_GPC['member']}%' or idcard like '%{$_GPC['member']}%' ) ";
        $bb .= " and openid in ( select from_user from " . tablename('tg_member') . " where uniacid = {$_W['uniacid']} {$key} ) ";
    }

    if (!empty($_GPC['status'])) {
        $status = intval($_GPC['status']);
        if ($status == 2) {
            $bb .= " and prize = 1 ";
        } elseif ($status == 3) {
            $bb .= " and status = 0 and prize = 0";
        } elseif ($status == 1) {
            $bb .= " and status = " . $status . " and prize = 0";
        }

    }

    $sql = "select * from " . tablename('tg_favorabler') . "  where uniacid = :uniacid  {$bb}  LIMIT " . ($page - 1) * $size . " , " . $size;
    file_put_contents(TG_DATA."data.log", var_export(array('data' => $dd , 'sql' => $sql), true).PHP_EOL, FILE_APPEND);
    $list = pdo_fetchall($sql, array(':uniacid' => $_W['uniacid']));
    foreach ($list as &$value) {
        $member = pdo_fetch("select * from " . tablename('tg_member') . " where openid = :openid", array(':openid' => $value['openid']));
        $coupon = pdo_fetch("select name from " . tablename('tg_favorable') . " where id = :id", array(':id' => $value['favorable_id']));
        $value['user'] = $member;
        $value['mobile'] = $member['mobile'];
        $value['idcard'] = $member['idcard'];
        $value['coupon'] = $coupon;
        $value['hexiao'] = pdo_fetchcolumn("select count(id) from " . tablename('tg_hexiao') . " where uniacid = '{$_W['uniacid']}' and favorabler_id = '{$value['id']}' ");
        unset($value);
    }

    $total = pdo_fetchall("select id from " . tablename('tg_favorabler') . " WHERE uniacid = {$_W['uniacid']} {$bb}");
    $total = count($total);

    if ($_W['uniacid'] == 4) {
//        die(json_encode($list));
    }
    $pager = pagination($total, $page, $size);

//    if (checksubmit('submit')) {
//        $name = trim($_GPC['name']);
//        $subtitle = trim($_GPC['subtitle']);
//        $person = trim($_GPC['person']);
////        die(json_encode(array('name' => $name , 'subtitle' => $subtitle , 'person' => $person)));
//        $sql = "select * from " .tablename('tg_favorable') ." where uniacid = :uniacid";
//        $params = array(':uniacid' => $_W['uniacid']);
//        if (empty($name) && empty($subtitle) && empty($person)){
//            message('请输入搜索条件！', web_url('goods/coupon_record', array('op' => 'display')), 'error');
//            exit();
//        }else{
//            if (!empty($name)){
//                $sql .= " and name like '%" .$name ."%' ";
//            }
//            if (!empty($subtitle)){
//                $sql .= " and subtitle like '%" .$subtitle ."%' ";
//            }
//            if (!empty($person)){
//                $sql .= " and person like '%" .$person ."%' ";
//            }
//        }
//
//        $list = pdo_fetchall($sql,$params);
//
//        $total = count($list);
//        $pager = pagination($total, $page, $size);
//        file_put_contents(TG_DATA."data.log", var_export(array('data' => $list , 'time' => $subtitle , 'person' => $person), true).PHP_EOL, FILE_APPEND);
//
//    }

//die(json_encode(array('data' => $list)));
//    $list = pdo_fetchall("SELECT * FROM " . tablename('tg_favorable') . " WHERE uniacid = '{$_W['uniacid']}' ");
    include wl_template('goods/coupon_record');
} elseif ($operation == 'post') {
    $id = intval($_GPC['id']);
    if (checksubmit('submit')) {
        $data = array(
            'uniacid' => $_W['uniacid'],
            'name' => $_GPC['name'],
            'subtitle' => $_GPC['subtitle'],
            'applicant' => $_GPC['applicant'],
            'up_limit' => $_GPC['up_limit'],
            'deadline' => strtotime($_GPC['deadline']),
            'pic' => $_GPC['pic'],
            'start_time' => strtotime($_GPC['start_time']),
            'end_time' => strtotime($_GPC['end_time']),
            'class_time' => $_GPC['class_time'],
            'person' => $_GPC['person'],
            'course' => $_GPC['course'],
            'address' => $_GPC['address'],
            'term' => $_GPC['term'],
            'salesman' => $_GPC['salesman']
        );
        if (!empty($id)) {
            pdo_update('tg_favorable', $data, array('id' => $id));
            message('更新优惠券成功！', web_url('goods/coupon_record', array('op' => 'display')), 'success');
        } else {
            pdo_insert('tg_favorable', $data);
            $id = pdo_insertid();
            message('添加优惠券成功！', web_url('goods/coupon_record', array('op' => 'display')), 'success');
        }

    }
    $coupon = pdo_fetch("select * from " . tablename('tg_favorable') . " where id=:id and uniacid=:uniacid limit 1", array(":id" => $id, ":uniacid" => $_W['uniacid']));
    include wl_template('goods/coupon_record');
} elseif ($operation == 'delete') {
    $id = intval($_GPC['id']);
    $coupon = pdo_fetch("SELECT * FROM " . tablename('tg_favorabler') . " WHERE id = $id");
//    die(json_encode(array('data' => $coupon)));
    if (empty($coupon)) {
        message('抱歉，优惠券记录不存在或是已经被删除！', web_url('goods/coupon_record', array('op' => 'display')), 'error');
    }
    pdo_delete('tg_favorabler', array('id' => $id));
    message('优惠券记录删除成功！', web_url('goods/coupon_record', array('op' => 'display')), 'success');
} elseif ($op == 'output') {

    set_time_limit(0);
    $coupon = trim($_GPC['coupon']);
    $member = trim($_GPC['member']);
    $bb = '';

    if (!empty($_GPC['coupon'])) {
        $c = trim($_GPC['coupon']);
        $keyword .= " and (name LIKE '%{$_GPC['coupon']}%')";

        $aa = pdo_fetchall('select id from ' . tablename('tg_favorable') . " where uniacid = {$_W['uniacid']} {$keyword}");
        $ee = pdo_fetchall('select id from ' . tablename('tg_member') . " where uniacid = {$_W['uniacid']} {$keyword1}");
        $bb .= ' and favorable_id in (' . 'select id from ' . tablename('tg_favorable') . " where uniacid = {$_W['uniacid']} {$keyword}" . ')';
    }
    if (!empty($_GPC['member'])) {
        $mem = trim($_GPC['member']);
        $key = " and (realname like '%{$_GPC['member']}%' or mobile like '%{$_GPC['member']}%' or idcard like '%{$_GPC['member']}%')";
        $bb .= ' and openid in (' . 'select from_user from ' . tablename('tg_member') . " where uniacid={$_W['uniacid']}  {$key}" . ')';
    }

    $sql = "select * from " . tablename('tg_favorabler') . "  where uniacid = :uniacid  {$bb}";
//    file_put_contents(TG_DATA."data.log", var_export(array('data' => $dd , 'sql' => $sql), true).PHP_EOL, FILE_APPEND);
    $orders = pdo_fetchall($sql, array(':uniacid' => $_W['uniacid']));
    foreach ($orders as &$value) {
        $member = pdo_fetch("select * from " . tablename('tg_member') . " where openid = :openid", array(':openid' => $value['openid']));
        $coupon = pdo_fetch("select name from " . tablename('tg_favorable') . " where id = :id", array(':id' => $value['favorable_id']));
        $value['user'] = $member;
        $value['mobile'] = $member['mobile'];
        $value['idcard'] = $member['idcard'];
        $value['coupon'] = $coupon;
    }
    $str = '花名册_' . date('ymdhis', time());
    /* 输入到CSV文件 */
    $html = "\xEF\xBB\xBF";
    /* 输出表头 */
    $filter = array('aa' => '编号', 'bb' => '真实姓名', 'cc' => '性别', 'dd' => '手机号', 'ee' => '身份证号', 'ff' => '领取优惠券名称'
//    , 'gg' => '报名截止日期',
//        'ii'=>'开始时间','jj'=>'结束时间','kk'=>'开课时间','ll'=>'适用人群','mm'=>'课程介绍','nn'=>'上课地址','oo'=>'使用须知'
    );
    foreach ($filter as $key => $title) {
        $html .= $title . "\t,";
    }
    $html .= "\n";
    foreach ($orders as $k => $v) {
        $orders[$k]['aa'] = $v['id'];
        $orders[$k]['bb'] = $v['user']['realname'];
        $orders[$k]['cc'] = $v['user']['sex'];
        $orders[$k]['dd'] = $v['mobile'];
        $orders[$k]['ee'] = $v['idcard'];
        $orders[$k]['ff'] = $v['coupon']['name'];
//        $orders[$k]['gg'] = date('y-m-d h:i' , $v['deadline']);
//        $orders[$k]['ii'] = date('y-m-d h:i' , $v['start_time']);
//        $orders[$k]['jj'] = date('y-m-d h:i' , $v['end_time']);
//        $orders[$k]['kk'] = $v['class_time'];
//        $orders[$k]['ll'] = $v['person'];
//        $orders[$k]['mm'] = $v['course'];
//        $orders[$k]['nn'] = $v['address'];
//        $orders[$k]['oo'] = $v['term'];

        foreach ($filter as $key => $title) {
            $html .= $orders[$k][$key] . "\t,";
        }
        $html .= "\n";
    }
    /* 输出CSV文件 */
    header("Content-type:text/csv");
    header("Content-Disposition:attachment; filename={$str}.csv");
    echo $html;
    exit();
} elseif ($op == 'prize') {

    $size = 10;
    $page = !empty($_GPC['page']) ? $_GPC['page'] : 1;
    $coupon = '';
    $member = '';
    $bb = '';
//    if (!empty($_GPC['coupon'])) {
//        $c = trim($_GPC['coupon']);
//        $keyword .= " and (name LIKE '%{$_GPC['coupon']}%')";
//
//        $aa = pdo_fetchall('select id from ' . tablename('tg_favorable') . " where uniacid = {$_W['uniacid']} {$keyword}");
//        $ee = pdo_fetchall('select id from ' . tablename('tg_member') . " where uniacid = {$_W['uniacid']} {$keyword1}");
//        $bb .= ' and favorable_id in (' . 'select id from ' . tablename('tg_favorable') . " where uniacid = {$_W['uniacid']} {$keyword}" . ')';
//    }
//    if (!empty($_GPC['member'])) {
//        $mem = trim($_GPC['member']);
//        $key = " and (realname like '%{$_GPC['member']}%' or mobile like '%{$_GPC['member']}%' or idcard like '%{$_GPC['member']}%')";
//        $bb .= ' and openid in (' . 'select from_user from ' . tablename('tg_member') . " where uniacid={$_W['uniacid']}  {$key}" . ')';
//    }

    $sql = "select * from " . tablename('tg_prize') . "  where uniacid = :uniacid  {$bb}  LIMIT " . ($page - 1) * $size . " , " . $size;
//    file_put_contents(TG_DATA."data.log", var_export(array('data' => $dd , 'sql' => $sql), true).PHP_EOL, FILE_APPEND);
    $list = pdo_fetchall($sql, array(':uniacid' => $_W['uniacid']));
    foreach ($list as &$value) {
        $member = pdo_fetch("select * from " . tablename('tg_member') . " where idcard = :idcard", array(':idcard' => $value['idcard']));
        $value['user'] = $member;
        $times = pdo_fetchall("select id from " . tablename('tg_favorabler') . " where status = 1 and openid in ( select openid from " . tablename('tg_member') . " where uniacid = :uniacid and idcard = :idcard)", array(':uniacid' => $_W['uniacid'], ':idcard' => $value['idcard']));
        $value['times'] = count($times);
    }

    $total = pdo_fetchall("select id from " . tablename('tg_prize') . " WHERE uniacid = {$_W['uniacid']} {$bb}");
    $total = count($total);

    $pager = pagination($total, $page, $size);
    include wl_template('goods/coupon_record');
} elseif ($operation == 'prize_post') {
//    $id = intval($_GPC['id']);
//    if (checksubmit('submit')) {

    $f_id = $_GPC['favorabler_id'];
    $idcard = $_GPC['idcard'];
    $times = pdo_fetchall("select id from " . tablename('tg_favorabler') . " where status = 1 and openid in ( select openid from " . tablename('tg_member') . " where uniacid = :uniacid and idcard = :idcard)", array(':uniacid' => $_W['uniacid'], ':idcard' => $idcard));
    $times = count($times);
    $data = array(
        'uniacid' => $_W['uniacid'],
        'idcard' => $idcard,
        'prize_user' => $_W['user']['username'],
        'prize_time' => TIMESTAMP,
        'prize_times' => $times
    );
//        die(json_encode(array('data' => $data)));
    if (!empty($id)) {
        pdo_update('tg_prize', $data, array('id' => $id));
        message('更新发奖记录成功！', web_url('goods/coupon_record', array('op' => 'prize')), 'success');
    } else {
        pdo_insert('tg_prize', $data);
        $id = pdo_insertid();
        pdo_update('tg_favorabler', array('prize' => 1), array('id' => $f_id));
        message('添加发奖记录成功！', web_url('goods/coupon_record', array('op' => 'prize')), 'success');
    }

//    }
//    $prize = pdo_fetch("select * from " . tablename('tg_prize') . " where id = :id and uniacid = :uniacid limit 1", array(":id" => $id, ":uniacid" => $_W['uniacid']));
//    include wl_template('goods/coupon_record');
} elseif ($operation == 'prize_delete') {
    $id = intval($_GPC['id']);
    $prize = pdo_fetch("SELECT * FROM " . tablename('tg_prize') . " WHERE id = $id");
//    die(json_encode(array('data' => $coupon)));
    if (empty($prize)) {
        message('抱歉，发奖记录不存在或是已经被删除！', web_url('goods/coupon_record', array('op' => 'prize')), 'error');
    }
    pdo_delete('tg_prize', array('id' => $id));
    message('发奖记录删除成功！', web_url('goods/coupon_record', array('op' => 'prize')), 'success');
} else {
    message('请求方式不存在');
}
exit();